<script setup>
import { onMounted, reactive, ref, provide } from 'vue'
import TabHead from './components/TabHead.vue'
import TableBody from './components/TableBody.vue'
import EditAndAdd from './components/EditAndAdd.vue'
import api from '@/api/index.js'
import { filesDown } from '@/utils/filesTool.js'

const props = defineProps({
  // 父组件要求的默认筛选参数
  params: { type: Object, default: () => ({}) }
})
// 加载状态
const loading = ref(false)
// 分页参数
const pageInfo = reactive({ current: 1, pageSize: 10, total: 0 })
// 表格数据
const tableData = ref([])
// 抽屉节点
const drawer = ref()
// 当前数据保存
const curRow = ref({})

// 初始化
const init = (params) => {
  pageInfo.current = 1
  pageInfo.pageSize = 10
  pageInfo.total = 0
  getList(params)
}

// 获取表格数据
const getList = async (params = {}) => {
  loading.value = true
  const data = {
    ...pageInfo,
    ...props.params,
    ...params
  }
  const {
    resultObject: { records, total }
  } = await api.getXsList(data)
  pageInfo.total = total
  tableData.value = records
  loading.value = false
}

// 新增数据
const addItem = () => {
  curRow.value = {}
  drawer.value.open()
}

// 编辑数据
const editItem = (item) => {
  curRow.value = { ...item, children: null }
  drawer.value.open()
}

// 关闭弹窗处理
const closeDrawer = () => {
  curRow.value = {}
}

// 搜索
const savePara = ref({})
const search = (params) => {
  savePara.value = params
  init(params)
}
// 页码变化
const pageChange = (page) => {
  pageInfo.current = page
  getList(savePara.value)
}
//数据导出
const exportToExcel = async () => {
  const {
    data: { url }
  } = await api.exportList()
  window.open(url, '_blank').focus()
}
onMounted(() => {
  init()
})
//下载导入模板
const upLoadMould = () => {
  const url =
    'https://www.xiaozhuzhnj.top/fileInfo/template/%E9%94%80%E5%94%AE%E8%AE%A2%E5%8D%95%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx'
  filesDown(url)
}
provide('tableData', tableData)
</script>

<template>
  <a-spin :spinning="loading" wrapperClassName="com-spin">
    <div class="com-full page">
      <div class="head">
        <TabHead
          @add="addItem"
          @init="search({})"
          @search="search"
          @exportToExcel="exportToExcel"
          @upLoadMould="upLoadMould"
        />
      </div>
      <div class="table">
        <TableBody
          @edit="editItem"
          @reload="getList(savePara)"
          :total="pageInfo.total"
          :pageNum="pageInfo.current"
          @pageChange="pageChange"
        />
      </div>
    </div>
    <EditAndAdd
      ref="drawer"
      :faMenuSltOpt="tableData"
      :curRow="curRow"
      @close="closeDrawer"
      @init="search({})"
      @reload="getList(savePara)"
    />
  </a-spin>
</template>

<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
  gap: 24px;

  .table {
    flex: 1;
    overflow: auto;
  }
}
</style>
